{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz\n",
      "step 100, entropy loss: 1.902616, l2_loss: 805.193054, total loss: 1.958979\n",
      "0.56\n",
      "step 200, entropy loss: 0.664573, l2_loss: 806.976257, total loss: 0.721062\n",
      "0.78\n",
      "step 300, entropy loss: 0.634558, l2_loss: 807.991516, total loss: 0.691118\n",
      "0.85\n",
      "step 400, entropy loss: 0.368051, l2_loss: 808.563782, total loss: 0.424651\n",
      "0.93\n",
      "step 500, entropy loss: 0.349145, l2_loss: 809.038940, total loss: 0.405778\n",
      "0.88\n",
      "step 600, entropy loss: 0.281290, l2_loss: 809.375916, total loss: 0.337947\n",
      "0.93\n",
      "step 700, entropy loss: 0.242394, l2_loss: 809.697266, total loss: 0.299072\n",
      "0.95\n",
      "step 800, entropy loss: 0.168864, l2_loss: 809.989990, total loss: 0.225563\n",
      "0.99\n",
      "step 900, entropy loss: 0.256524, l2_loss: 810.257202, total loss: 0.313242\n",
      "0.96\n",
      "step 1000, entropy loss: 0.141047, l2_loss: 810.460449, total loss: 0.197779\n",
      "0.99\n",
      "0.9338\n",
      "step 1100, entropy loss: 0.240147, l2_loss: 810.650635, total loss: 0.296892\n",
      "0.92\n",
      "step 1200, entropy loss: 0.342923, l2_loss: 810.839905, total loss: 0.399682\n",
      "0.91\n",
      "step 1300, entropy loss: 0.159254, l2_loss: 811.042664, total loss: 0.216027\n",
      "0.9\n",
      "step 1400, entropy loss: 0.188845, l2_loss: 811.201660, total loss: 0.245629\n",
      "0.94\n",
      "step 1500, entropy loss: 0.300985, l2_loss: 811.334473, total loss: 0.357778\n",
      "0.92\n",
      "step 1600, entropy loss: 0.170496, l2_loss: 811.489319, total loss: 0.227300\n",
      "0.98\n",
      "step 1700, entropy loss: 0.228635, l2_loss: 811.614075, total loss: 0.285448\n",
      "0.95\n",
      "step 1800, entropy loss: 0.181275, l2_loss: 811.731689, total loss: 0.238097\n",
      "0.97\n",
      "step 1900, entropy loss: 0.090871, l2_loss: 811.827393, total loss: 0.147699\n",
      "0.99\n",
      "step 2000, entropy loss: 0.159718, l2_loss: 811.945862, total loss: 0.216554\n",
      "0.97\n",
      "0.9521\n",
      "step 2100, entropy loss: 0.219343, l2_loss: 812.046204, total loss: 0.276186\n",
      "0.95\n",
      "step 2200, entropy loss: 0.250562, l2_loss: 812.159363, total loss: 0.307413\n",
      "0.98\n",
      "step 2300, entropy loss: 0.100540, l2_loss: 812.240601, total loss: 0.157396\n",
      "0.98\n",
      "step 2400, entropy loss: 0.070287, l2_loss: 812.342468, total loss: 0.127151\n",
      "0.98\n",
      "step 2500, entropy loss: 0.096393, l2_loss: 812.407166, total loss: 0.153261\n",
      "0.99\n",
      "step 2600, entropy loss: 0.158762, l2_loss: 812.441956, total loss: 0.215633\n",
      "0.97\n",
      "step 2700, entropy loss: 0.076595, l2_loss: 812.535767, total loss: 0.133472\n",
      "0.97\n",
      "step 2800, entropy loss: 0.074774, l2_loss: 812.589539, total loss: 0.131655\n",
      "0.98\n",
      "step 2900, entropy loss: 0.171831, l2_loss: 812.655762, total loss: 0.228717\n",
      "0.96\n",
      "step 3000, entropy loss: 0.205702, l2_loss: 812.710266, total loss: 0.262592\n",
      "0.94\n",
      "0.9652\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "# First convolutional layer - maps one grayscale image to 32 feature maps.\n",
    "with tf.name_scope('conv1'):\n",
    "  h_conv1 = tf.layers.conv2d(x_image, 32, [5,5],\n",
    "                             padding='SAME',\n",
    "                             activation=tf.nn.relu)\n",
    " \n",
    "\n",
    "# Pooling layer - downsamples by 2X.\n",
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.layers.max_pooling2d(h_conv1, pool_size=[2,2],\n",
    "                        strides=[2, 2], padding='VALID')\n",
    "\n",
    "# Second convolutional layer -- maps 32 feature maps to 64.\n",
    "with tf.name_scope('conv2'):\n",
    "  h_conv2 = tf.layers.conv2d(h_pool1, 64, [5,5],\n",
    "                             padding='SAME',\n",
    "                             activation=tf.nn.relu)\n",
    "\n",
    "# Second pooling layer.\n",
    "with tf.name_scope('pool2'):\n",
    "  h_pool2 = tf.layers.max_pooling2d(h_conv2, pool_size=[2,2],\n",
    "                        strides=[2, 2], padding='VALID')\n",
    "\n",
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "with tf.name_scope('fc1'):\n",
    "  h_pool2_flat = tf.layers.flatten(h_pool2)\n",
    "  h_fc1 = tf.layers.dense(h_pool2_flat, 1024, activation=tf.nn.relu)\n",
    "\n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "with tf.name_scope('fc2'):\n",
    "  y = tf.layers.dense(h_fc1_drop, 10, activation=None)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 0.01\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
